#include <simplemq/simplemq_mqtt.hpp>
#include <date_utilits.h>
#include "BaseCmdParam.h"
/************************************************************************/
/* MQTT client 连接测试                                                 */
/************************************************************************/
using namespace simplemq;

// 命令行参数解析器
class ClientConfig : public gdface::BaseClientConfig {
public:
	const std::string PARAM_CHANNEL_NAME = "channel";
	const std::string PARAM_USERNAME = "username";
	const std::string PARAM_PASSWORD = "password";
	/** 频道名，默认'c1' */
	std::string channel;
	std::string username;
	std::string password;
	ClientConfig() :gdface::BaseClientConfig(DEFAULT_MQTT_PORT), channel(), password() {
		cmdparam.add<std::string>(PARAM_CHANNEL_NAME, 'c', "channel name", false, "c1");
		cmdparam.add<std::string>(PARAM_USERNAME, 'u', "username for authorization", false, "");
		cmdparam.add<std::string>(PARAM_PASSWORD, 'a', "password for authorization", false, "");
	}
	~ClientConfig() = default;
	void afterParse() {
		gdface::BaseClientConfig::afterParse();
		channel = cmdparam.get<std::string>(PARAM_CHANNEL_NAME);
		username = cmdparam.get<std::string>(PARAM_USERNAME);
		password = cmdparam.get<std::string>(PARAM_PASSWORD);
	}
};

std::string now_str() {
	auto now = std::chrono::system_clock::now();
	auto mills = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
	return date::format_iso8601(mills);
}
int
main(int argc, char *argv[]) {
	ClientConfig param;
	param.parse(argc, argv);
	ClientManager cmgr;
	try {

		auto cm = cmgr.getClient(mq_client_params{ param.host, param.port, param.password ,param.username});
		for (int i = 0; i < 100; ++i) {
			auto pubmsg = ::mqtt::make_message(param.channel, now_str().append(" ").append(std::to_string(i)));
			pubmsg->set_qos(2);
			cm->publish(pubmsg);
		}
	}
	catch (const std::exception &e)
	{
		SAMPLE_ERR("{}:{}", typeid(e).name(), e.what());
	}
}
